package com.heima.ai;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "alibaba.ai")
@Slf4j
public class AIService {
    String apiKey;
    String model="qwen-plus";

    /**
     * 调用大模型
     * @param userContent 用户的问题
     * @param systemContent 系统的内容
     * @return 大模型的回答
     */
    public  String callWithMessage(String userContent,String systemContent){
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(userContent)
                .build();
        GenerationParam param = GenerationParam.builder()
                .apiKey(apiKey)
                .model(model)
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        GenerationResult call = null;
        try {
            call = gen.call(param);
        } catch (NoApiKeyException | InputRequiredException e) {

            log.error("调用失败："+e.getMessage()+"返回如下"+JsonUtils.toJson(call));
            throw new RuntimeException(e);
        }

        //返回大模型的回答
        return call.getOutput().getChoices().get(0).getMessage().getContent();
    }

    /**
     * 调用大模型
     * @param userContent 用户内容
     *                    默认的系统内容是：You are a helpful assistant.
     * @return 大模型的回答
     */
    public  String callWithMessage(String userContent){
        return callWithMessage(userContent,"You are a helpful assistant.");
    }

    /**
     * 调用大模型
     * @param userContent 用户的问题
     * @param longAnswer 是否开启连续对话
     * @return 大模型的回答
     */
    public String callWithMessage(String userContent,boolean longAnswer){
        return callWithMessage(userContent,"You are a helpful assistant.");
    }
}
